using AutoMapper;
using B.S.NewMedical.Api.Read.Application.Command.Test;
using B.S.NewMedical.Api.Read.DTOS.Test;
using B.S.NewMedical.Domain.Doctor;
using B.S.NewMedical.ErrorCode;
using B.S.NewMedical.Infrastructure.Interface;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.NewMedical.Api.Read.Application.Handler.Test
{
    /// <summary>
    /// 获取所有检验项目分类处理程序
    /// </summary>
    public class GetAllTestCategoriesHandler : IRequestHandler<GetAllTestCategoriesCommand, ApiResult<List<TestCategoryDto>>>
    {
        private readonly IBaseRepository<TestCategoryModel> _testCategoryRepository;
        private readonly ILogger<GetAllTestCategoriesHandler> _logger;
        private readonly IMapper _mapper;

        public GetAllTestCategoriesHandler(
            IBaseRepository<TestCategoryModel> testCategoryRepository,
            ILogger<GetAllTestCategoriesHandler> logger,
            IMapper mapper)
        {
            _testCategoryRepository = testCategoryRepository;
            _logger = logger;
            _mapper = mapper;
        }

        public async Task<ApiResult<List<TestCategoryDto>>> Handle(GetAllTestCategoriesCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始获取所有检验项目分类");

                // 查询所有未删除的检验项目分类
                var testCategories = await _testCategoryRepository.GetAll()
                    .Where(tc => !tc.IsDeleted)
                    .OrderBy(tc => tc.Id)
                    .ToListAsync(cancellationToken);

                // 转换为DTO
                var testCategoryDtos = _mapper.Map<List<TestCategoryDto>>(testCategories);

                return new ApiResult<List<TestCategoryDto>>
                {
                    Code = ApiEnum.Success,
                    Msg = "获取检验项目分类成功",
                    Data = testCategoryDtos
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取检验项目分类时发生异常");
                return new ApiResult<List<TestCategoryDto>>
                {
                    Code = ApiEnum.Error,
                    Msg = "获取检验项目分类失败：" + ex.Message,
                    Data = new List<TestCategoryDto>()
                };
            }
        }
    }
} 